import 'dart:async';

/// stream 创建方案
void main() {
  // testTake();
  // testWhile();
  // testWhere();
  testDistinct();
  // testSkip();
  // testSkipWhile();
  // testMap();
}

/// 指定最大长度
void testTake() {
  Duration interval = Duration(seconds: 1);
  int i = 0;
  //take(5) 指定最大提取
  Stream.periodic(interval, (data) => data).take(5).listen((event) {
    print("event:$event");
  }).onDone(() {
    print("done ");
  });
}

///循环
void testWhile() {
  Duration interval = Duration(seconds: 1);
  int i = 0;
  //take(5) 指定最大提取
  Stream.periodic(interval, (data) => data).takeWhile((element) {
    print("takeWhile element:$element");
    return element <= 2;
  }).listen((event) {
    print("event:$event");
  }).onDone(() {
    print("done ");
  });
}

/// 条件过滤
void testWhere() {
  Duration interval = Duration(seconds: 2);
  int i = 0;
  //take(5) 指定最大提取
  Stream.periodic(interval, (data) => data)
      .takeWhile((element) {
        return element <= 5;
      })
      .where((data) => data % 2 == 0)
      .listen((event) {
        print("event:$event");
      })
      .onDone(() {
        print("done ");
      });
}

/// 去重
void testDistinct() {
  var data = [1, 2, 'a', 'a', 1, 1, 3, 4];
  Stream.fromIterable(data).distinct().listen((event) {
    print("testDistinct listen:$event");
  }).onDone(() {
    print("testDistinct done");
  });
}
//跳过执行
void testSkip() {
  var data = [1, 2, 'a', 'a', 1, 1, 3, 4];
  Stream.fromIterable(data).skip(2).listen((event) {
    print("testDistinct listen:$event");
  }).onDone(() {
    print("testDistinct done");
  });
}

//跳过循环条件
void testSkipWhile() {

  Stream.periodic(Duration(seconds: 1),(data) => data)
  .takeWhile((element) => element <= 6)
  .skipWhile((element){
    return element <= 3;
  }).listen((event) {
    print("testDistinct listen:$event");
  }).onDone(() {
    print("testDistinct done");
  });
}


// 数据变换 map
void testMap() {

  Stream.periodic(Duration(seconds: 1),(data) => data)
      .takeWhile((element) => element <= 6)
      .skipWhile((element){
    return element <= 3;
  }).map((event) => event * 10)
  .listen((event) {
    print("testDistinct listen:$event");
  }).onDone(() {
    print("testDistinct done");
  });
}
